library("shiny")
library("plotly")

source("funkce.R")

stahnout = function(file, fmat){
  df = read.table(file)
  rownames(df) = c(paste("Si", 1:16, sep = ""), paste("Ni", 17:64, sep = ""))
  mnestab = read.table(fmat)
  df = as.matrix(df) %*% as.matrix(mnestab)
}

ui = fluidPage( 
  fluidRow(
    column(6,
           h2("Nestabilni"),
           plotlyOutput("plotN"),
           h3("DOS"),
           tableOutput("dosN"),
           h3("COHP"),
           tableOutput("cohpN")
    ),
    column(6,
           h2("Stabilni"),
           plotlyOutput("plotS"),
           h3("DOS"),
           tableOutput("dosS"),
           h3("COHP"),
           tableOutput("cohpS")
    )
  )
)

server = function(input, output) {
  
  val = reactiveValues(
    snestab = stahnout("soubory.dat\\GB-unstable.txt", "soubory.dat\\GB-unstable_mat.txt"),
    sstab = stahnout("soubory.dat\\GB-stable.txt", "soubory.dat\\GB-stable_mat.txt"),
    dosN = read.csv("ulozeno\\vse_dos_nestab.csv")[,-1],
    dosS = read.csv("ulozeno\\vse_dos_stab.csv")[,-1],
    cohpN = read.csv("ulozeno\\vse_nestab.csv", sep = ";", dec = ","),
    cohpS = read.csv("ulozeno\\vse_stab.csv")[,-1]
  )
  
  output$plotN <- renderPlotly({
    snestab = val$snestab
    ma = max(snestab)
    bar = (substr(rownames(snestab),1,2) == "Ni") +1
    
    plot_ly(as.data.frame(snestab), x = ~V1, y = ~V2, z = ~V3, color = as.factor(bar), colors = c('#BF382A', '#0C4B8E'),
            text = ~paste('Atom:', rownames(snestab)), source = "nestab") %>%
      layout(scene = list(xaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)"),
                          yaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)"),
                          zaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)")),
             showlegend = FALSE)%>%
      add_markers() 
  })
  output$text = renderPrint({
    d <- event_data("plotly_click", source = "nestab")$pointNumber + 1
    if (is.null(d)) "Click events appear here (double-click to clear)" else d
    })
  
  output$dosN = renderTable({
    if (event_data("plotly_click", source = "nestab")$curveNumber == 0) {
      d <- event_data("plotly_click", source = "nestab")$pointNumber + 1
    } else {
      d <- event_data("plotly_click", source = "nestab")$pointNumber + 17
    }
    if (length(d) == 0) return(NULL) else {
      df = val$dosN
      if (d > nrow(df)) d = d -nrow(df)
      df$out = normalize(df$out)
      return(df[as.character(df$t) == rownames(val$snestab)[d],])
    }
  })
  output$cohpN = renderTable({
    #browser()
    if (event_data("plotly_click", source = "nestab")$curveNumber == 0) {
      d <- event_data("plotly_click", source = "nestab")$pointNumber + 1
    } else {
      d <- event_data("plotly_click", source = "nestab")$pointNumber + 17
    }
    if (length(d) == 0) return(NULL) else {
      df = val$cohpN
      if (d > nrow(val$snestab)) d = d -nrow(val$snestab)
      df$out = normalize(df$out)
      df$podil = df$ocop/df$ovor
      return(df[as.character(df$x) == rownames(val$snestab)[d] | as.character(df$y) == rownames(val$snestab)[d],])
    }
  })
  
  output$plotS <- renderPlotly({
    sstab = val$sstab
    ma = max(sstab)
    bar = (substr(rownames(sstab),1,2) == "Ni") +1
    
    plot_ly(as.data.frame(sstab), x = ~V1, y = ~V2, z = ~V3, color = as.factor(bar), colors = c('#BF382A', '#0C4B8E'),
            text = ~paste('Atom:', rownames(sstab)), source = "stab") %>%
      layout(scene = list(xaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)"),
                          yaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)"),
                          zaxis = list(range = c(0, ma),
                                       gridcolor="rgb(255,255,255)",
                                       zerolinecolor="rgb(255,255,255)")),
             showlegend = FALSE) %>%
      add_markers()
  })
  
  output$dosS = renderTable({
    #browser()
    if (event_data("plotly_click", source = "stab")$curveNumber == 0) {
      d <- event_data("plotly_click", source = "stab")$pointNumber + 1
    } else {
      d <- event_data("plotly_click", source = "stab")$pointNumber + 17
    }
    if (length(d) == 0) return(NULL) else {
      df = val$dosS
      if (d > nrow(df)) d = d -nrow(df)
      df$out = normalize(df$out)
      return(df[as.character(df$t) == rownames(val$sstab)[d],])
    }
  })
  output$cohpS = renderTable({
    #browser()
    if (event_data("plotly_click", source = "stab")$curveNumber == 0) {
      d <- event_data("plotly_click", source = "stab")$pointNumber + 1
    } else {
      d <- event_data("plotly_click", source = "stab")$pointNumber + 17
    }
    if (length(d) == 0) return(NULL) else {
      df = val$cohpS
      if (d > nrow(val$dosS)) d = d -nrow(val$dosS)
      df$out = normalize(df$out)
      df$podil = df$ocop/df$ovor
      return(df[as.character(df$x) == rownames(val$sstab)[d] | as.character(df$y) == rownames(val$sstab)[d],])
    }
  })
}

shinyApp(ui = ui, server = server)